module IndexParser

using Utils
using Printf

struct IndexGroup
    name::AbstractString
    indexes::Vector{Int32}
end

struct Index
    groups::Vector{IndexGroup}
end

function gen_ndx_from_file(indexfilename::AbstractString)::Index
    lines = readlines(indexfilename)
    group_name_lines = findall.(x -> occursin.(r"\[.+\]", x), (lines, ))[1]
    group_names = [strip(match(r"\[(.+)\]", s).captures[1]) for s in lines[group_name_lines]]
    groups = Vector{IndexGroup}()
    for (i, l) in enumerate(group_name_lines)
        sec_start = l + 1
        sec_end = (i == length(group_name_lines) ? length(lines) : group_name_lines[i + 1] - 1)
        atom_list = Vector{Int32}()
        for l in lines[sec_start:sec_end]
            for a in parse.(Int32, split(l))
                push!(atom_list, a)
            end
        end
        push!(groups, IndexGroup(group_names[i], atom_list))
    end
    return Index(groups)
end

function list_groups(ndx)
    println("\nGroups of current index file:")
    for (i, k) in enumerate(ndx.groups)
        @printf("%3d): %-15s%10d atoms\n", i - 1, k.name, length(k.indexes))  # 迎合Gromacs的从0开始排序
    end
end

end # module
